package Algorithm

import "fmt"

// dispatch 将数据分发到指定设备和通道
func (r *AlgoPlugin) dispatch(deviceID string, channelID int, data []byte) {
	ch := r.getOrCreateChannel(deviceID, channelID)

	select {
	case ch.DataCh <- data:
		fmt.Printf("device %s channel %d recv data: %d bytes\n", deviceID, channelID, len(data))
		break
	default:
		fmt.Printf("device %s channel %d full\n", deviceID, channelID)
	}
}

type AlgoData struct {
	DeviceID  string
	ChannelID int
	Payload   []byte
}

// decodeAlgoData 示例函数：根据你的协议解析 data
func decodeAlgoData(data []byte) *AlgoData {
	return &AlgoData{
		DeviceID:  "deviceA",
		ChannelID: 1,
		Payload:   data,
	}
}

func (r *AlgoPlugin) getOrCreateDevice(deviceID string) *Device {
	r.mu.Lock()
	defer r.mu.Unlock()

	if dev, ok := r.devices[deviceID]; ok {
		return dev
	}

	dev := &Device{
		DeviceID: deviceID,
		Channels: make(map[int]*DeviceChannel),
	}
	r.devices[deviceID] = dev
	return dev
}
func (r *AlgoPlugin) getOrCreateChannel(deviceID string, channelID int) *DeviceChannel {
	dev := r.getOrCreateDevice(deviceID)

	r.mu.Lock()
	defer r.mu.Unlock()

	if ch, ok := dev.Channels[channelID]; ok {
		return ch
	}

	ch := &DeviceChannel{
		ChannelID: channelID,
		DataCh:    make(chan []byte, r.conf.MaxCacheSize),
	}
	dev.Channels[channelID] = ch
	return ch
}
